package com.example.binarytree;

/**
 * @author Jonathan
 * 2021/4/16 19:39
 * 满二叉树判断
 */
public class FullBinaryTree {
    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }


    public static class Info {
        public int height;
        public int nodes;

        public Info(int height, int nodes) {
            this.height = height;
            this.nodes = nodes;
        }
    }

    public boolean isFullBinaryTree(TreeNode root) {
        Info info = process(root);
        // 2^height==nodes
        return (1 << info.height) - 1 == info.nodes;
    }

    public Info process(TreeNode x) {
        if (x == null) {
            return new Info(0, 0);
        }

        Info left = process(x.left);
        Info right = process(x.right);

        int height = Math.max(left.height, right.height) + 1;
        int nodes = left.nodes + right.nodes + 1;
        return new Info(height, nodes);
    }
}
